var listButton = document.
getElementsByClassName('list')[0];
var musicList = document.
getElementsByClassName('music-list')[0];
var closeList = document.
getElementsByClassName('close-list')[0];
var audio=document.getElementById('audio');
var pause=document.getElementsByClassName('icon-play')[0];

// 获取元素
// 应该使用 querySelector 获取唯一元素
var recordImg = document.querySelector('.rotate-play');

// 歌曲名
var musicTitle = document.getElementById('music-title');

// 歌曲作者
var author = document.getElementById('author-name');

// 总进度条
var progressTotal = document.getElementsByClassName('pgs-total')[0];
// 播放的进度
var progressPlay = document.getElementsByClassName('pgs-play')[0];

// 已播放时长
var playedTime = document.getElementsByClassName('played-time')[0];

var totalTime = document.getElementsByClassName('audio-time')[0];

// 音量控制
var volumnButton = document.getElementsByClassName('volumn')[0];
var volumnTogger = document.getElementById('volumn-togger');

// 播放模式按钮
var mode = document.getElementsByClassName('mode')[0];
// 上一首
var  skipForward = document.getElementsByClassName('s-left')[0];
// 下一首
var skipBackward = document.getElementsByClassName('s-right')[0];

// 倍速
var speed = document.getElementsByClassName('speed')[0];
// MV
var MV = document.getElementsByClassName('MV')[0];

// 展开列表功能
listButton.addEventListener('click',
     function(event){
        musicList.classList.remove('list-card-hide');
        // 让列表显示出来的动画
        musicList.classList.add('list-card-show');
        // 展示列表
        musicList.style.display = 'block';
        closeList.style.display = 'block';
        closeList.addEventListener('click',
                 function(){
                 // 让列表隐藏起来的动画
                 musicList.classList.remove('list-card-show');
                 musicList.classList.add('list-card-hide');
                 // 让列表隐藏起来
                 musicList.style.display = 'none';
                 closeList.style.display = 'none';
                 }
            );
     }
);
var musicId = 0;  // 用于列表点击
var index = 0;    // 用于上下首切换
var musics = ['Up.mp3','Love.mp3','MM.mp3','likeJENNIE.mp3']; 
// 修改初始化音乐函数
function initMusic(){
    audio.src = 'MP3/' + musics[index];
    audio.load();
    // 修改这里：使用canplay事件来获取正确的duration
    audio.oncanplay = function(){
        totalTime.innerText = transTime(audio.duration);
    }
}
initMusic();
// 播放音乐
function initAndPlay(){
     initMusic();
     pause.classList.remove('icon-play');
     pause.classList.add('icon-pause');
     audio.play();
     rotateRecord();
}

// 播放模式设置
var modeId = 1;
mode.addEventListener('click',function(event)
{
    modeId = modeId + 1;
    if(modeId > 3){
        modeId = 1;
    }
    mode.style.backgroundImage = url('img/mode${modeId}.png');
});

// 音频播放结束时
audio.onended = function () {
  if (modeId == 2) {
    // 顺序播放：直接调用下一首逻辑
    skipBackward.click();
  } else if (modeId == 3) {
    // 随机播放
    var oldId = musicId;
    do {
      musicId = Math.floor(Math.random() * musics.length);
    } while (musicId == oldId && musics.length > 1);
    initAndPlay();
  }
};

// 暂停播放
// 播放/暂停控制
// 修正后的播放控制
document.querySelector('.icon-play').addEventListener('click', function() {
    if(audio.paused) {
        audio.play();
        document.querySelector('.rotate-play').style.animationPlayState = 'running';
        this.classList.replace('icon-play', 'icon-pause');
    } else {
        audio.pause();
        document.querySelector('.rotate-play').style.animationPlayState = 'paused';
        this.classList.replace('icon-pause', 'icon-play');
    }
});
document.querySelector('.icon-play').addEventListener('click', function() {
    rotateRecord(); // 确保调用旋转函数
});
// 列表点击切换音乐
document.querySelector('.music0').addEventListener('click', function() {
    musicId = 0;
    initAndPlay();
});

// 唱片旋转
// 修改旋转控制函数
function rotateRecord(){
    recordImg.style.animationPlayState = 'running';
}
function rotateRecordStop(){
    recordImg.style.animationPlayState = 'paused';
}

// 更新进度条
audio.addEventListener('timeupdate',updateProgress);
// 修改更新进度条函数
function updateProgress(){
    // 修正这里：使用audio.duration而不是audio.ondurationchange
    var value = audio.currentTime / audio.duration;
    progressPlay.style.width = value * 100 + '%';
    playedTime.innerText = transTime(audio.currentTime);
    pause.classList.remove('icon-play');
    pause.classList.add('icon-pause');
}
// 点击进度条 
progressTotal.addEventListener('mousedown',function(event)
{
    if (!audio.paused || audio.currentTime !=0)
    {
        var pgsWidth = progressTotal.getBoundingClientRect().width;
        var rate = event.offsetX / pgsWidth;
        audio.currentTime = audio.duration * rate;
        updateProgress(audio);
    }
});

//音频播放时间换算
function transTime(value) {
  var time = '';
  var h = parseInt(value / 3600);
  value %= 3600;
  var m = parseInt(value / 60);
  var s = parseInt(value % 60);
  if (h > 0) {
    time = formatTime(h + ':' + m + ':' + s);
  } else {
    time = formatTime(m + ':' + s);
  }

  return time;
}

// 格式化时间显示，补零对齐
function formatTime(value) {
  var time = '';
  var s = value.split(':');
  var i = 0;
  for (; i < s.length - 1; i++) {
    time += s[i].length == 1 ? '0' + s[i] : s[i];
    time += ':';
  }
  time += s[i].length == 1 ? '0' + s[i] : s[i];

  return time;
}

// 控制音量
var lastVolumn = 70;
// audio.volume规定值是0-1
audio.volume = lastVolumn / 100;
audio.addEventListener('timeupdate',updateVolumn);
// 滑动音量
function updateVolumn(){
    audio.volume = volumnTogger.value / 100;
}
//点击静音
volumnButton.addEventListener('click',function(){
    audio.muted = !audio.muted;
    if(audio.muted){
        lastVolumn = volumnTogger.value;
        volumnTogger.value = 0;
        volumnButton.style.backgroundImage = "url('IMG/静音.png')";
    }else{
        volumnTogger.value = lastVolumn;
        volumnButton.style.backgroundImage = "url('IMG/音量.png')";
    }
});

// 上一首
var muscics = [
    ['likeJENNIE','jennie']
]
// 上一首
skipForward.addEventListener('click', function() {
    musicId = musicId - 1;
    if (musicId < 0) {
        musicId = musics.length - 1; // 循环到最后一首
    }
    initAndPlay();
});

// 下一首 
skipBackward.addEventListener('click', function() {
    musicId = (musicId + 1) % musics.length; // 自动循环
    initAndPlay();
});

// 倍速功能（这里直接暴力解决）
speed.addEventListener('click', function (event) {
  var speedText = speed.innerText;
  if (speedText == '1.0X') {
    speed.innerText = '1.5X';
    audio.playbackRate = 1.5;
  } else if (speedText == '1.5X') {
    speed.innerText = '2.0X';
    audio.playbackRate = 2.0;
  } else if (speedText == '2.0X') {
    speed.innerText = '0.5X';
    audio.playbackRate = 0.5;
  } else if (speedText == '0.5X') {
    speed.innerText = '1.0X';
    audio.playbackRate = 1.0;
  }
});

// MV功能
MV.addEventListener('click', function (event) {
  // 向新窗口传值
  var storage_list = window.sessionStorage;
  storage_list['musicId'] = musicId;
  window.open('video.html');
});

// 暴力捆绑列表音乐
document.getElementById('music0').addEventListener('click', function (event) {
  musicId = 0;
  initAndPlay();
});
document.getElementById('music1').addEventListener('click', function (event) {
  musicId = 1;
  initAndPlay();
});
document.getElementById('music2').addEventListener('click', function (event) {
  musicId = 2;
  initAndPlay();
});
document.getElementById('music3').addEventListener('click', function (event) {
  musicId = 3;
  initAndPlay();
});

// 刷新唱片旋转角度
function refreshRotate() {
  recordImg.classList.add('rotate-play');
}

// 使唱片旋转
function rotateRecord() {
  // animationPlayState属性用于控制CSS动画的播放状态
  recordImg.style.animationPlayState = 'running';
}

// 停止唱片旋转
function rotateRecordStop() {
  recordImg.style.animationPlayState = 'paused';
}